/*
 * 
 *
 *
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.Page;
import com.hboxs.asl.Pageable;
import com.hboxs.asl.dao.BankCardDao;
import com.hboxs.asl.entity.BankCard;
import com.hboxs.asl.entity.Member;
import org.springframework.stereotype.Repository;

import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * Dao - 银行卡
 */
@Repository("bankCardDaoImpl")
public class BankCardDaoImpl extends BaseDaoImpl<BankCard, Long> implements BankCardDao {

    @Override
    public BankCard findBankCardByNumber(String number) {
        if (number == null) {
            return null;
        }
        String jpql = "select bankcard from BankCard bankcard where lower(bankcard.cardNumber) = lower(:cardNumber)";
        try {
            return entityManager.createQuery(jpql, BankCard.class).setFlushMode(FlushModeType.COMMIT).setParameter("cardNumber", number).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public Page<BankCard> findPage(Member member, Pageable pageable) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<BankCard> criteriaQuery = criteriaBuilder.createQuery(BankCard.class);
        Root<BankCard> root = criteriaQuery.from(BankCard.class);
        criteriaQuery.select(root);
        if (member != null) {
            criteriaQuery.where(criteriaBuilder.equal(root.get("member"), member));
        }
        return super.findPage(criteriaQuery, pageable);
    }
}
